<template>
  <div class="index-container">
    <div class="table-header-btn-wrap" style="height: 30px">
      <el-button @click="onClickSearch" v-loading="listLoading">刷新</el-button>
      <el-button @click="create" v-loading="listLoading">添加房间类型</el-button>
    </div>
    <div class="table-wrap" style="height: calc(100% - 100px)">
      <el-table :data="rooms" border v-loading="listLoading" height="100%" :empty-text="'数据为空'">

        <el-table-column prop="name" label="名称" width="120px">
        </el-table-column>

        <el-table-column prop="photo" label="封面" width="160px">
          <template #default="scope">
            <img style="width: 130px" v-if="scope.row.photo"
                 :src="uploadServer +  '/upload/image/' +scope.row.photo"
                 class="avatar"/>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="费用" width="70px">
          <template #default="scope">
            {{ scope.row.price }}元
          </template>
        </el-table-column>

        <el-table-column prop="people" label="最多容纳人数" width="120px">
        </el-table-column>

        <el-table-column prop="bedCount" label="床位数量" width="90px">
        </el-table-column>

        <el-table-column prop="bedSize" label="床的大小" width="150px">
        </el-table-column>

        <el-table-column prop="equipment" label="设备" width="280px">
        </el-table-column>

        <el-table-column prop="spares" label="备用品" width="280px">
        </el-table-column>


        <el-table-column prop="excerpt" label="操作" width="100px">
          <template #default="scope">
            <el-button type="success" @click="edit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-wrap"
         style="height: 40px;margin-top: 20px;display: flex;align-items: center;justify-content: space-between;">
      <div class="span" style="font-size: 14px;color: #333;margin-right: 20px;">总数：{{ total }}</div>
      <el-pagination
          small
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="query.page"
          class="mt-4"
          @current-change="pageChange"
          :page-size="query.page_size"
      />
    </div>

    <el-dialog v-model="createDialog" :title="dialogModel==='create'?'添加房间类型':'修改房间类型'" width="760px"
               :close-on-click-modal="false"
    >
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rulesType"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
      >
        <el-form-item label="名称" prop="name" style="max-width: 400px;width: 100%">
          <el-input v-model="ruleForm.name"/>
        </el-form-item>
        <el-form-item label="封面" prop="photo" style="max-width: 800px;width: 100%">
          <el-upload
              class="avatar-uploader"
              :action="uploadServer + '/upload/upload'"
              multiple
              :headers="headers"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              accept=".png,.jpg"
          >
            <img v-if="ruleForm.photo" :src="uploadServer +  '/upload/image/' +ruleForm.photo"
                 class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="费用" prop="price" style="max-width: 400px;width: 100%">
          <el-input v-model="ruleForm.price"/>
        </el-form-item>
        <el-form-item label="最多容纳人数" prop="people" style="max-width: 400px;width: 100%">
          <el-input v-model="ruleForm.people"/>
        </el-form-item>
        <el-form-item label="床位数量" prop="bedCount" style="max-width: 500px;width: 100%">
          <el-input v-model="ruleForm.bedCount"/>
        </el-form-item>
        <el-form-item label="床的大小" prop="bedSize" style="max-width: 500px;width: 100%">
          <el-input type="textarea" rows="3" v-model="ruleForm.bedSize"/>
        </el-form-item>
        <el-form-item label="设备" prop="equipment" style="max-width: 800px;width: 100%">
          <el-input type="textarea" rows="8" v-model="ruleForm.equipment"/>
        </el-form-item>
        <el-form-item label="备用品" prop="spares" style="max-width: 800px;width: 100%">
          <el-input type="textarea" rows="8" v-model="ruleForm.spares"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="dialogModel === 'create'">
            添加
          </el-button>
          <el-button type="primary" @click="submitEditForm(ruleFormRef)" v-else>
            修改
          </el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref} from "vue";
import $api from "@/api";
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus'
import type {FormInstance, FormRules, UploadProps} from "element-plus";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import TypeSelect from '@/components/TypeSelect.vue'

const validateFloat2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入'))
  } else {
    var pattern = /^\d+(\.\d{1,2})?$/
    if (pattern.test(value)) {
      callback()
    } else {
      callback(new Error('请输入数字，最多两位小数点'))
    }
  }
}

const locale = zhCn
const router = useRouter()

const clickOpen = (row: any) => {
  router.push('/book/' + row.id)
}


const dialogModel = ref('create') //create edit
const createDialog = ref(false)
var createLoading = ref(false)
const create = () => {
  dialogModel.value = 'create'
  createDialog.value = true
  ruleForm.id = null
  ruleForm.name = ""
  ruleForm.price = ""
  ruleForm.photo = ""
  ruleForm.people = ""
  ruleForm.bedCount = ""
  ruleForm.bedSize = ""
  ruleForm.equipment = ""
  ruleForm.spares = ""
}
const edit = (row: any) => {
  dialogModel.value = 'edit'
  createDialog.value = true
  ruleForm.id = row.id
  ruleForm.name = row.name
  ruleForm.price = row.price
  ruleForm.photo = row.photo
  ruleForm.people = row.people
  ruleForm.bedCount = row.bedCount
  ruleForm.bedSize = row.bedSize
  ruleForm.equipment = row.equipment
  ruleForm.spares = row.spares
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: null,
  name: '',
  price: '',
  photo: '',
  people: '',
  bedCount: '',
  bedSize: '',
  equipment: '',
  spares: '',
})
const rulesType = reactive<FormRules>({
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'},
    {min: 1, max: 30, message: '长度限制在 1 ~ 30 个字符', trigger: 'blur'},
  ],
  photo: [
    {required: true, message: '请上传图书封面', trigger: 'blur'},
  ],
  price: [
    {required: true, message: '请输入费用', trigger: 'blur'},
    {validator: validateFloat2, trigger: 'blur'}
  ]
})
/**
 * @description 添加接口调用
 * @param formEl
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (createLoading.value) {
        return
      }
      createLoading.value = true
      $api.typeApi.create(ruleForm).then(res => {
        createLoading.value = false
        ElNotification({
          title: '成功',
          message: '创建房间类型成功！',
          type: 'success',
        })
        createDialog.value = false
        search()
      }).catch(() => {
        createLoading.value = false
      })
    } else {

    }
  })
}

/**
 * 上传文件
 */

const uploadServer = import.meta.env.VITE_SERVER

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  console.log(response)
  if (response.code === 200) {
    ruleForm.photo = response.data
    ElNotification({
      title: '成功',
      message: '上传成功！',
      type: 'success',
    })
  } else {
    if (response.detail) {
      ElMessage.error(response.detail)
    } else {
      ElMessage.error(response.message)
    }
  }
}
const handleAvatarError: UploadProps['onError'] = (
    error: Error
) => {
  ElMessage.error('上传失败！')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  var pattern = /\.png$|\.PNG$|\.jpg$|\.JPG$|\.jpeg$|\.JPEG$/i
  if (!pattern.test(rawFile.name)) {
    ElMessage.error('请选择 图片 文件，后缀名为  .png、.PNG、.jpg、.JPG、.jpeg 或 .JPEG。')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('文件大小不能超过 4MB!')
    return false
  }
  return true
}

var tokenName = localStorage.getItem('tokenName')
var tokenValue = localStorage.getItem('tokenValue')
const headers = {
  [tokenName]: tokenValue
}


onMounted(() => {
  search()
})

/**
 * 查询房间
 */

var listLoading = ref(false) //列表接口是否在加载

const total = ref(0) //总数

const query = reactive({
  page: 1,
  page_size: 20,
})
const pageChange = (page: number) => {
  query.page = page
  getList()
}
const onClickSearch = () => {
  search()
}

const search = () => {
  query.page = 1
  getList()
}

const rooms = ref([])
const getList = () => {
  listLoading.value = true
  $api.typeApi.list(query).then((res: any) => {
    total.value = res.total
    rooms.value = res.results
    listLoading.value = false
  }).catch(() => {
    listLoading.value = false
  })
}


const submitEditForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (createLoading.value) {
        return
      }
      createLoading.value = true
      $api.typeApi.edit(ruleForm).then(res => {
        createLoading.value = false
        ElNotification({
          title: '成功',
          message: '修改图书成功！',
          type: 'success',
        })
        createDialog.value = false
        search()
      }).catch(() => {
        createLoading.value = false
      })
    } else {

    }
  })
}
</script>
<style>
.avatar-uploader .avatar {
  width: 280px;
  height: 150px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 280px;
  height: 150px;
  text-align: center;
}
</style>
<style scoped lang="scss">
.index-container {
  padding: 20px;
  width: 100%;
  height: 100%;
}

.table-wrap {
  margin-top: 20px;
}

.excerpt {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>